<template>
    <div>
        <el-text size="large">销售信息</el-text>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-form :model="queryForm" label-width="120px" style="max-width: 100%; margin: 0 auto;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="销售单号">
                        <el-input-number v-model="queryForm.sales_id as number" :min="0" :step="1" step-strictly placeholder="销售单号" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="商品ID">
                        <el-input-number v-model="queryForm.goods_id as number" :min="0" :step="1" step-strictly placeholder="请输入ID" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="商品名字">
                        <el-autocomplete v-model="queryForm.goods_name" :fetch-suggestions="fetchSuggestions('goods_name')" placeholder="请输入商品名字"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="销售价格">
                        <el-input-number v-model="queryForm.sales_price as number" :min="0" :step="0.01" step-strictly placeholder="价格" style="width: 100%;">
                            <template #prefix>￥</template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="销售数量">
                        <el-input-number v-model="queryForm.sales_quantity as number" :min="0" :step="1" step-strictly placeholder="销售数量" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="时间范围">
                        <el-date-picker v-model="queryForm.sales_time" show-now editable clearable type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY/MM/DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="备注">
                        <el-autocomplete v-model="queryForm.remarks" :fetch-suggestions="fetchSuggestions('remarks')" placeholder="请输入备注"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="searchSales" :loading="loading" :icon="Search">查询</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="success" @click="openAddDialog" :icon="Plus">新增</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-table :data="paginatedSalesList" v-if="paginatedSalesList.length > 0" show-summary :summary-method="getSummaries">
            <el-table-column prop="sales_id" label="销售单号" sortable></el-table-column>
            <el-table-column prop="goods_id" label="商品ID" sortable></el-table-column>
            <el-table-column prop="goods_name" label="商品名字" sortable></el-table-column>
            <el-table-column prop="sales_price" label="销售价格 ￥" sortable></el-table-column>
            <el-table-column prop="sales_quantity" label="销售数量" sortable></el-table-column>
            <el-table-column prop="sales_cost" label="销售费用 ￥" sortable></el-table-column>
            <el-table-column prop="sales_time" label="销售时间" sortable>
                <template #default="scope">
                    {{ new Date(scope.row.sales_time).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) }}
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" sortable></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-container style="width: 4.5rem;">
                        <el-button type="primary" :icon="Edit" circle @click="openEditDialog(scope.row)"></el-button>
                        <el-button type="danger" :icon="Delete" circle @click="openDeleteDialog(scope.row)"></el-button>
                    </el-container>
                </template>
            </el-table-column>
        </el-table>
        <el-empty v-else description="没找到数据呢，亲~"></el-empty>
        <el-pagination
            v-if="total > 0"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
        <AddDialog ref="addSalesDialog" @refresh="searchSales" />
        <EditDialog ref="editSalesDialog" @refresh="searchSales" />
        <DeleteDialog ref="deleteSalesDialog" @refresh="searchSales" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import axios, { AxiosError } from 'axios';
import { ElMessage } from 'element-plus';
import AddDialog from '@/components/AddDialog.vue';
import EditDialog from '@/components/EditDialog.vue';
import DeleteDialog from '@/components/DeleteDialog.vue';
import type { SalesQueryForm, Sales, FormItem } from '@/types/interface';
import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue';

const queryForm = reactive<SalesQueryForm>({
    sales_id: null as any,
    goods_id: null as any,
    goods_name: '',
    sales_price: null,
    sales_quantity: null,
    sales_time: null as any,
    remarks: ''
});

const salesList = ref<Sales[]>([
    {
        sales_id: 1,
        goods_id: 101,
        goods_name: '商品A',
        sales_price: 100.0,
        sales_quantity: 2,
        sales_cost: 200.0,
        sales_time: new Date(),
        remarks: '备注A'
    },
    {
        sales_id: 2,
        goods_id: 102,
        goods_name: '商品B',
        sales_price: 150.0,
        sales_quantity: 1,
        sales_cost: 150.0,
        sales_time: new Date(),
        remarks: '备注B'
    }
]);
const total = ref(salesList.value.length);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 分页后的销售信息列表
const paginatedSalesList = computed(() => {
    if (!salesList.value || salesList.value.length === 0) {
        return [];
    }
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return salesList.value.slice(start, end);
});

// 获取建议的函数
function fetchSuggestions(field: keyof SalesQueryForm): (queryString: string, cb: (suggestions: { value: string }[]) => void) => void {
    return async (queryString: string, cb: (suggestions: { value: string }[]) => void) => {
        if (!queryString) {
            cb([]);
            return;
        }
        try {
            const response = await axios.get(`/api/sales/suggestions`, {
                params: { field, query: queryString }
            });
            cb(response.data.map((item: string) => ({ value: item })));
        } catch (error) {
            console.error(`获取${field}建议失败:`, error);
            cb([]);
        }
    };
}

// 查询销售信息
async function searchSales() {
    try {
        loading.value = true;
        const response = await axios.get('/api/sales', {
            params: {
                ...queryForm,
                page: 1,
                pageSize: 1000 // 假设最大查询1000条数据
            }
        });
        salesList.value = response.data.items;
        total.value = response.data.total;
        currentPage.value = 1;
        ElMessage.success('查询销售信息成功');
    } catch (error: any) {
        console.error('查询销售信息失败:', error);
        ElMessage.error('查询销售信息失败' + error.response.data.error);
    } finally {
        loading.value = false;
    }
}

// 计算汇总信息
function getSummaries(param: { columns: any; data: any }) {
    const { columns, data } = param;
    const summaries = [] as any;
    columns.forEach((column: any, index: number) => {
        if (index === 0) {
            summaries[index] = '总计';
        } else if (index === 2) {
            const uniqueGoodsNames = new Set(data.map((item: any) => item.goods_name));
            summaries[index] = uniqueGoodsNames.size;
        } else if (index === 4) {
            summaries[index] = data.reduce((sum: number, item: any) => sum + Number(item.sales_quantity), 0);
        } else if (index === 5) {
            summaries[index] = data.reduce((sum: number, item: any) => sum + Number(item.sales_cost), 0).toFixed(2);
        } else {
            summaries[index] = '';
        }
    });
    return summaries;
}

// 处理页码变化
function handlePageChange(page: number) {
    currentPage.value = page;
}

function handleSizeChange(size: number) {
    pageSize.value = size;
    currentPage.value = 1;
}

const addSalesDialog = ref();
const editSalesDialog = ref();
const deleteSalesDialog = ref();

// 打开新增对话框
function openAddDialog() {
    addSalesDialog.value.openDialog({
        title: '新建销售信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: '', rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '销售价格', prop: 'sales_price', value: null, rules: [
                { required: true, message: '销售价格不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '销售价格不能小于0', trigger: 'blur' }
            ] },
            { label: '销售数量', prop: 'sales_quantity', value: null, rules: [
                { required: true, message: '销售数量不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '销售数量不能小于0', trigger: 'blur' }
            ] },
            { label: '销售时间', prop: 'sales_time', value: null, rules: [
                { required: true, message: '销售时间不能为空', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: '', rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            addSalesDialog.value.visible = false;
            ElMessage({
                message: '已取消新建',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await addSalesDialog.value.formRef.validate();
                await axios.post('/api/sales', addSalesDialog.value.formData);
                ElMessage({
                    message: '新建销售信息记录成功',
                    type: 'success',
                });
                addSalesDialog.value.visible = false;
                searchSales();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开编辑对话框
function openEditDialog(row: Sales) {
    editSalesDialog.value.openDialog({
        title: '编辑销售信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: row.goods_name, rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '销售价格', prop: 'sales_price', value: row.sales_price, rules: [
                { required: true, message: '销售价格不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '销售价格不能小于0', trigger: 'blur' }
            ] },
            { label: '销售数量', prop: 'sales_quantity', value: row.sales_quantity, rules: [
                { required: true, message: '销售数量不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '销售数量不能小于0', trigger: 'blur' }
            ] },
            { label: '销售时间', prop: 'sales_time', value: row.sales_time, rules: [
                { required: true, message: '销售时间不能为空', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: row.remarks, rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            editSalesDialog.value.visible = false;
            ElMessage({
                message: '已取消编辑',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await editSalesDialog.value.formRef.validate();
                await axios.put(`/api/sales/${row.sales_id}`, editSalesDialog.value.formData);
                ElMessage({
                    message: '编辑销售信息记录成功',
                    type: 'success',
                });
                editSalesDialog.value.visible = false;
                searchSales();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开删除对话框
function openDeleteDialog(row: Sales) {
    deleteSalesDialog.value.openDialog({
        title: '删除销售信息记录',
        content: `是否删除销售单号为 ${row.sales_id} 的记录？`,
        handleCancel: () => {
            deleteSalesDialog.value.visible = false;
            ElMessage({
                message: '已取消删除',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await axios.delete(`/api/sales/${row.sales_id}`);
                ElMessage({
                    message: '删除销售信息记录成功',
                    type: 'success',
                });
                deleteSalesDialog.value.visible = false;
                searchSales();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        }
    });
}

onMounted(() => {
    // 初始化时加载数据
    searchSales();
});
</script>

<style scoped>
.el-form-item {
    margin: 10px 0;
}
.el-input,
.el-button {
    width: 100%;
}
.el-form {
    padding: 20px;
}
.el-form-item .el-form-item__label {
    padding-right: 20px;
}
</style>